package org.zhang.shortlink.admin.controller;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.zhang.shortlink.admin.remote.dto.req.ShortLinkCreateDTO;
import org.zhang.shortlink.admin.remote.dto.req.ShortLinkPageDTO;
import org.zhang.shortlink.admin.remote.dto.resp.ShortLinkCreateVO;
import org.zhang.shortlink.admin.remote.dto.resp.ShortLinkPageVO;
import org.zhang.shortlink.common.convention.result.Result;
import org.zhang.shortlink.common.convention.result.Results;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

@RestController
public class ShortLinkController {

    /**
     * 创建短链接
     */
    @PostMapping("/api/short-link/admin/v1/create")
    public Result<ShortLinkCreateVO> createShortLink(@RequestBody ShortLinkCreateDTO requestParam) {
        HttpRequest httpRequest = HttpUtil.createPost("http://127.0.0.1:56002/api/short-link/link/v1/create").body(JSON.toJSONString(requestParam));
        HttpResponse execute = httpRequest.execute();
        return Results.success(JSON.parseObject(execute.body(), ShortLinkCreateVO.class));
    }

    /**
     * 分页查询短链接
     */
    @GetMapping("/api/short-link/admin/v1/page")
    public Result<IPage<ShortLinkPageVO>> pageShortLink(ShortLinkPageDTO requestParam) {
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("gid", requestParam.getGid());
        requestMap.put("current", requestParam.getCurrent());
        requestMap.put("size", requestParam.getSize());
        String actualUrl = HttpUtil.get("http://127.0.0.1:56002/api/short-link/link/v1/page", requestMap);
        Type type = new TypeReference<Result<IPage<ShortLinkPageVO>>>() {
        }.getType();
        return JSON.parseObject(actualUrl, type);
    }
}